// ESP8266 wifi

#ifndef _NET_ESP8266_H
#define _NET_ESP8266_H

#include <ESP8266WiFi.h>

extern void d_home_update();

// 函数声明
bool connect_wifi(String ssid, String password);
void init_wifi();

// 连接WIFI
void init_wifi()
{
	// WiFi.mode(WIFI_STA);
	String wifi_info = "";
	d_home_update("info", "WiFi...");


	bool flag_connected = false;
	int connect_num = 0;
	while(flag_connected == false && connect_num < 2) {
		if(connect_num == 0) {
			Serial.println("连接主WIFI");
			wifi_time_s = millis();
			flag_connected = connect_wifi(ssid_1, password_1);
		}
		else if(connect_num == 1){
			Serial.println("连接备用WIFI");
			wifi_time_s = millis();
			flag_connected = connect_wifi(ssid_2, password_2);
		}
		connect_num++;
	}

	
	if(flag_connected) {
		wifi_info = "WiFi...OK";
		Serial.println("连接成功");
	}
	else {
		wifi_info = "WiFi...Failed";
		Serial.println("连接失败");
		flag_net = false;
	}	
	
	d_home_update("info", wifi_info);
}

bool connect_wifi(String ssid, String password) {
	bool check = true;
	// WiFi初始化
	WiFi.begin(ssid, password);
	unsigned long connect_time;
	int current_ssid = 1;
	bool flag_stop_try = false;
	while (WiFi.status() != WL_CONNECTED && flag_net)
	{
		// check_btn();
		delay(100);
		Serial.print(".");
		connect_time = int(millis() - wifi_time_s);
		d_home_update("info", "WiFi...(" + String((wifi_timeout - connect_time) / 1000) + ")");
		if (connect_time >= wifi_timeout)
		{			
			check = false;
			break;
		}
	}
	return check;
}

#endif